package kuaidi.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import kuaidi.api.services.ChakuaidiService;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by John on 2016/10/27.
 */

public class RetroManager {
    private static volatile RetroManager instance=null;
    private static Retrofit retrofit;
    OkHttpClient client;
    private static final int DEFAULT_READ_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_WRITE_TIMEOUT = 15 * 1000;

    private RetroManager(String url){
        initOkhttpClient();
        initRetrofit(url);
    }

    public static RetroManager getInstance(String baseurl){
        if (instance==null){
            synchronized (RetroManager.class){
                if (instance==null){
                    instance=new RetroManager(baseurl);
                }
            }
        }
        return instance;
    }

    private void initRetrofit(String url) {
        if (retrofit==null){
            retrofit=new Retrofit.Builder()
                    .client(client)
                    .baseUrl(url)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }
    }

    private void initOkhttpClient() {
        if (client==null){
            client=new OkHttpClient.Builder()
                    .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(DEFAULT_CONNECT_TIMEOUT,TimeUnit.MILLISECONDS)
                    .writeTimeout(DEFAULT_WRITE_TIMEOUT,TimeUnit.MILLISECONDS)
                    .build();
        }
    }
    public Gson getGson(){
        return new GsonBuilder()
                .serializeNulls()
//                .setDateFormat()
                .create();
    }
    public ChakuaidiService getChaxunkuaidiService(){
        return retrofit.create(ChakuaidiService.class);
    }
}
